package com.es.piomessages.ui;

import java.util.Arrays;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.Toast;

import com.es.piomessages.R;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;

public class FacebookDialog extends DialogFragment {
	
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		super.onCreateDialog(savedInstanceState);
		
		publish();
		
		return ProgressDialog.show(getActivity(),getString(R.string.sharing),getString(R.string.loading),true,true,
				new DialogInterface.OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				Session.getActiveSession().close();

			}
		});
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Session session = Session.getActiveSession();
		Session.saveSession(session, outState);
	}
	  
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(getActivity(), requestCode,
				resultCode, data);
	}
		
	private void publish() {
		
		Session.OpenRequest auth = new Session.OpenRequest(this);
		String[] permissions = {"publish_stream"};
		auth.setPermissions(Arrays.asList(permissions));
		auth.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);

		auth.setCallback(new Session.StatusCallback() {
		    @Override
		    public void call(Session session, SessionState state, Exception exception) {
		        switch(state) {

		            case OPENING:
		                System.out.println("OPENING");
		                break;              

		            case OPENED: 
		                System.out.println("OPENED");
		                publishStory();
		                break;

		            case CREATED: 
		                System.out.println("CREATED");
		                break;

		            case CREATED_TOKEN_LOADED: 
		                System.out.println("CREATED_TOKEN_LOADED");
		                break;

		            case OPENED_TOKEN_UPDATED: 
		                System.out.println("OPENED_TOKEN_UPDATED");
		                break;

		            case CLOSED: 
		                System.out.println("CLOSED");
		                break;      

		            case CLOSED_LOGIN_FAILED: 
		            	Toast.makeText(getActivity(), getString(R.string.face_error), Toast.LENGTH_LONG).show();
		            	getDialog().dismiss();
		                System.out.println("CLOSED_LOGIN_FAILED");
		                break;                          
		        }
		    }
		});

		Session session = new Session.Builder(getActivity()).setApplicationId(getString(R.string.app_id)).build();
		Session.setActiveSession(session);
		session.openForPublish(auth);
	}
	
	private void publishStory(){
		
		Session session = Session.getActiveSession();
		
		Bundle postParams = new Bundle();
		postParams.putString("name", getString(R.string.face_title));
		postParams.putString("caption", getString(R.string.face_header));
		postParams.putString("description", getArguments().getString("msg"));
		postParams.putString("picture", "http://img28.imageshack.us/img28/9971/jesusvv.jpg");
		//postParams.putString("link", "https://sites.google.com/site/onepiosmessageperday/");

		final Request.Callback callback= new Request.Callback() {
			public void onCompleted(Response response) {
				FacebookRequestError error = response.getError();
				if (error != null) {
					Toast.makeText(getActivity(),
							getString(R.string.face_error),
							Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(getActivity(), 
							getString(R.string.face_sent),
							Toast.LENGTH_LONG).show(); 
				}
				
				getDialog().dismiss();
			}
		};
	     
		Request request = new Request(session, "me/feed", postParams, 
                          HttpMethod.POST, callback);

		RequestAsyncTask task = new RequestAsyncTask(request);
		task.execute();
		
	}
	
}